using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Data;
using MaskData;

namespace DBProxy
{
	public class AccessQuery : IQueryMask
	{
		private DBConnectionService _DBService = DBConnectionService.Instance();
		public MaskNodes GetChildNodes(ITypesReader reader, MaskNode node, String maskNodeId)
		{
			List<ElementType> types = reader.GetNodeTypesByID(maskNodeId);
			MaskNodes nodes = null;

			//String tableName = DBConnectionService.GetTableNameByID(maskNodeID);
			//if (tableName != "")
			//{
			//    String sqlString = "select * from "
			//    + tableName
			//    + " where "
			//    + node.GetMaskNodeIDField();
			//    +" = '"
			//    + node.GetMaskNodeIDValue()
			//    + "'";
			//    DataTable table = DBConnectionService.GetDataTable(sqlString, tableName);
			//    AddNodes(nodes, table);
			//}

			return nodes;

		}
		public MaskNodes QueryByNavigateNode(ITypesReader reader, NavigateTreeNode navigateNode)
		{
			//List<ElementType> types = reader.GetNodeTypesByID(navigateNode.NodeID);
			MaskNodes nodes = new MaskNodes(reader, navigateNode.NodeID);

			//////////////////////////////////////////////////////////////////////////
			//make sure the field name of condition exist in the types of this Mask node.
			//////////////////////////////////////////////////////////////////////////
			if (navigateNode.Condition != null)
			{
				bool fieldExist = false;
				String conditionFieldName = navigateNode.Condition.FieldName;
				foreach (ElementType type in nodes.ListTypes)
				{
					if (type.FieldName == conditionFieldName)
					{
						fieldExist = true;
						break;
					}
				}
				Debug.Assert(fieldExist);
			}
			//end check.

			String tableName = _DBService.GetTableNameByID(navigateNode.NodeID);
			if (tableName != "")
			{
				String sqlString = "select * from "
					+ tableName;
				if (navigateNode.Condition != null)
				{
					sqlString += " where " + navigateNode.Condition.GetSQLString();
				}
				DataTable table = _DBService.GetDataTable(sqlString, tableName);
				AddNodes(nodes, table);
			}
			return nodes;
		}
		private void AddNodes(MaskNodes nodes, DataTable table)
		{
			foreach (DataRow row in table.Rows)
			{
				MaskNode node = new MaskNode(nodes.Types);
				foreach (KeyValuePair<String, ElementType> typePair in nodes.Types)
				{
					MaskElement element = typePair.Value.CreateMaskElement(row[typePair.Value.FieldName]);
					node.AddElement(element);
				}
				nodes.Add(node);
			}
		}
	}
}

